package com.upbos.upm.settings;

import com.upbos.core.util.StringPool;
import com.upbos.upm.entity.User;
import com.upbos.upm.entity.UserCfg;
import com.upbos.upm.user.UserCfgUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettingsService {

    @Resource
    private SettingsDao settingsDao;

    private final String[] keys = {"layout", "layout.menu.theme", "layout.sider.topFirstLevelMenu", "layout.sider.leftMenuWidth",  "layout.top.width", "layout.theme.color"};

    public User getUser(String uid) {
        return settingsDao.getUser(uid);
    }

    public List<UserCfg> listLayoutCfg(String uid) {

        return UserCfgUtils.listUserCfg(uid, keys);
    }

    public Map<String, Object> getSecurityCfg(String uid) throws Exception {

        User user = settingsDao.getUserWithPassword(uid);

        Map<String, Object> res = new HashMap<>(2);
//        res.put("pwdStrength", PwdStrengthUtils.checkPasswordStrength(EncryptUtils.decrypt(user.getPassword(), Constants.PASSWORD_ENCRYPT_KEY)));
        if (user.getEmail() != null && !StringPool.EMPTY.equals(user.getEmail())) {
            int pos = user.getEmail().indexOf("@");
            if (pos > 0) {
                String hideEmail = user.getEmail().substring(0, pos / 2) + "****" + user.getEmail().substring(pos, user.getEmail().length());
                res.put("email", hideEmail);
            } else {
                res.put("email", null);
            }
        } else {
            res.put("email", null);
        }
        return res;
    }

    public void saveUserCfg(User user) {
        settingsDao.updateUser(user);
    }

    public void saveLayoutCfg(String uid, List<UserCfg> list) {
        settingsDao.deleteUserCfg(uid, list);
        settingsDao.insertUserCfg(uid, list);
    }

    public void restoreDefaultLayoutCfg(String uid) {
        List<UserCfg> list = new ArrayList<>();
        for (String key : keys) {
            UserCfg cfg = new UserCfg();
            cfg.setKey(key);
            list.add(cfg);
        }
        settingsDao.deleteUserCfg(uid, list);
    }
}
